1、promise是异步的，主要使用三个api进行处理，微任务（queueMicrotask），监听（MutationObserver），setTimeout，跟进兼容性依次处理



<script>
  function asyncFunc(callback) {
    if(typeof queueMicrotask === 'function') {
      queueMicrotask(callback)
    }else if(typeof MutationObserver === 'function') {
      const observer = new MutationObserver(callback)
      observer.observe(document.body, {
        childList: true
      })
    }else if(typeof setTimeout === 'function') {
      setTimeout(callback)
    }
  }

  const PENDING = 'pending'
  const FULFILLED = 'fulfilled'
  const REJECTED = 'rejected'
  class MyPromise {
    constructor(executor) {
      this.state = PENDING
      this.result = undefined
      this.resolveCallbacks = []
      this.rejectCallbacks = []
      const resolve = (result) => {
        if (this.state === PENDING) {
          this.state = FULFILLED
          this.result = result
          this.resolveCallbacks.forEach((callback) => {
            callback(result)
          })
        }
      }
      const reject = (result) => {
        if (this.state === PENDING) {
          this.state = REJECTED
          this.result = result
          this.rejectCallbacks.forEach((callback) => {
            callback(result)
          })
        }
      }
      executor(resolve, reject)
    }

    then(onFulfilled, onRejected) {
      onFulfilled =
        typeof onFulfilled === 'function' ? onFulfilled : (value) => value
      onRejected =
        typeof onRejected === 'function'
          ? onRejected
          : (reason) => {
              throw reason
            }
      if (this.state === FULFILLED) {
        asyncFunc(() => {
          onFulfilled(this.result)
        })
      }
      if (this.state === REJECTED) {
        asyncFunc(() => {
          onRejected(this.result)
        })
      }
      if (this.state === PENDING) {
        this.resolveCallbacks.push(() => {
          asyncFunc(() => {
            onFulfilled(this.result)
          })
        })
        this.rejectCallbacks.push(
          () => {
            asyncFunc(() => {
              onRejected(this.result)
            })
          }
        )
      }
    }
  }

  console.log('top')
  const p1 = new MyPromise((resolve, reject) => {
    resolve(1)
  })
  p1.then((res) => {
    console.log(res)
  })
   console.log('bottom')
</script>
